package com.chookss.home.rank;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.StudyPlanEntiry;
import com.chookss.home.studyPlan.StudyPlanDetailActivity;
import com.chookss.home.studyPlan.StudyPlanTaskDetailActivity;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;

@SuppressLint("ValidFragment")
public class RankFragment extends Fragment implements OnRefreshListener, OnLoadMoreListener {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.ivTimeArrow)
    ImageView ivTimeArrow;
    @BindView(R.id.ivAccessArrow)
    ImageView ivAccessArrow;
    @BindView(R.id.ivUserArrow)
    ImageView ivUserArrow;
    @BindView(R.id.llTime)
    LinearLayout llTime;
    @BindView(R.id.llDayType0)
    LinearLayout llDayType0;
    @BindView(R.id.llDayType1)
    LinearLayout llDayType1;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.srlView)
    ConsecutiveScrollerLayout srlView;
    private RankAdapter adapter;
    private RankAdapter1 adapter1;
    private ArrayList<RankEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int dayType = 0;//0 全部 1 每天（游客） 2 每周（粉丝） 3 每月（会员）
    private boolean isEnd = false;//是否到底
    private int timeSort = 0, empNumSort = -1, visitNumSort = -1;  //0倒序1正序
    private RefreshLayout refreshLayout;

    public RankFragment(int dayType) {
        this.dayType = dayType;
    }

    public RankFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rank, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    private void init() {
        if (dayType == 5) {
            llDayType0.setVisibility(View.VISIBLE);
            llDayType1.setVisibility(View.GONE);
            rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
            adapter = new RankAdapter(R.layout.item_rank, mContext, list);
            rv.setAdapter(adapter);
        } else {
            if (dayType == 2) {
                tvTime.setText("周期");
            } else if (dayType == 4) {
                tvTime.setText("月份");
            } else {
                tvTime.setText("日期");
            }
            llDayType0.setVisibility(View.GONE);
            llDayType1.setVisibility(View.VISIBLE);
            rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
            adapter1 = new RankAdapter1(R.layout.item_rank1, mContext, list,dayType);
            rv.setAdapter(adapter1);
        }
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        if(dayType!=5){
            toRefresh();
        }
    }


    @Override
    public void onLoadMore(RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        if (isEnd) {//has next page
            MyToast.show("没有更多数据了");
            loadEnd();
        } else {
            currentPage++;
            getData();
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        toRefresh();
    }

    private void toRefresh() {
        isEnd = false;
        currentPage = 1;
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        map.put("dayType", dayType + "");
        map.put("type", "0");

        if (dayType == 5) {
            if (timeSort == 0) {
                map.put("timeSort", "desc");
            } else if (timeSort == 1) {
                map.put("timeSort", "asc");
            }
        } else {
            if (empNumSort == 0) {
                map.put("empNumSort", "desc");
            } else if (empNumSort == 1) {
                map.put("empNumSort", "asc");
            }
            if (visitNumSort == 0) {
                map.put("visitNumSort", "desc");
            } else if (visitNumSort == 1) {
                map.put("visitNumSort", "asc");
            }
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RankEntity>>>() {
        }.getType(), null, Urls.selectSuYuanList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RankEntity>>() {
            @Override
            public void onSuccess(List<RankEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    if (dayType == 5) {
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter1.notifyDataSetChanged();
                    }
                }
                if (srlView == null || llNone == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    int oldNum = list.size();
                    list.addAll(data);
                    if (dayType == 5) {
                        adapter.notifyItemRangeChanged(oldNum, data.size());
                    } else {
                        adapter1.notifyItemRangeChanged(oldNum, data.size());
                    }
                    rv.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        rv.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }


    @OnClick({R.id.llTime, R.id.llAccess, R.id.llUsers})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llTime:
                if (timeSort == 0) {
                    timeSort = 1;
                    ivTimeArrow.setBackgroundResource(R.drawable.iv_paixu_down);
                } else {
                    timeSort = 0;
                    ivTimeArrow.setBackgroundResource(R.drawable.iv_paixu_up);
                }
                toRefresh();
                break;
            case R.id.llAccess:
                empNumSort=-1;
                ivUserArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                if (visitNumSort == 0) {
                    visitNumSort = 1;
                    ivAccessArrow.setBackgroundResource(R.drawable.iv_paixu_down);
                } else {
                    visitNumSort = 0;
                    ivAccessArrow.setBackgroundResource(R.drawable.iv_paixu_up);
                }
                toRefresh();
                break;
            case R.id.llUsers:
                visitNumSort=-1;
                ivAccessArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                if (empNumSort == 0) {
                    empNumSort = 1;
                    ivUserArrow.setBackgroundResource(R.drawable.iv_paixu_down);
                } else {
                    empNumSort = 0;
                    ivUserArrow.setBackgroundResource(R.drawable.iv_paixu_up);
                }
                toRefresh();
                break;
        }
    }


    private void loadEnd() {
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore(true);
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh(true);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
